<?php
/**
* 当前城市类
* @author moufer<moufer@163.com>
* @copyright (C)2001-2007 Moufersoft
*/
!defined('IN_MUDDER') && exit('Access Denied');

class ms_city extends ms_base
{
	
	public static $citys = null;

	public static function get_citys()
	{
		if(is_null(static::$citys)) {
			$citys = G('loader')->variable('area');
			if($citys) foreach ($citys as $city) {
				static::$citys[$city['aid']] = $city;
			}
		}
		return static::$citys;
	}

	public static function form_id($city_id)
	{
		$citys = static::get_citys();
		if($citys[$city_id] && $citys[$city_id]['enabled']) {
			return $citys[$city_id];
		}
		return false;
	}

	/**
	 * 获取单城市
	 * @param  boolean $ues_default 是否取默认城市
	 * @return array
	 */
	public static function form_single($ues_default = false)
	{
		$citys = static::get_citys();
		//只有一个城市，就返回这个城市
		if(count($citys) == 1) {
			$city = array_pop($citys);
			return $city;
		}
	    $enable_citys = array();
	    foreach($citys as $val) {
	        if($val['enabled']) {
	        	if($ues_default && $val['aid'] == S('city_id')) {
	        		$city = $val;
					return $city;
	        	}
	            $enable_citys[] = $val;
	        }
	    }
	    if(count($enable_citys) == 1) {
	    	$city = array_pop($enable_citys);
	    	return $city;
	    }
	    return false;
	}

	/**
	 * 取得一个默认城市
	 * 通过IP地址以及后台默认设置的城市来获取
	 * @return [type] [description]
	 */
	public static function form_default()
	{
		if($city = static::from_ip()) {
			return $city;
		}
		$citys = static::get_citys();
		if($citys) foreach($citys as $val) {
			if($val['aid'] == S('city_id') && $val['enabled']) {
				return $val;
			}
		}
		return false;
	}

	/**
	 * 通过IP地址来获取城市
	 * @param  string $ip ip地址
	 * @return ms_city
	 */
	public static function from_ip($ip = null)
	{
		$ipaddr_obj = new ms_ipaddress();
		if(!is_null($ip)) {
			$ipaddr_obj->set_ip($ip);
		}
	    $addr = $ipaddr_obj->get_address();
	    if($addr && !is_numeric($addr)) {
	        $citys = static::get_citys();
	        if($citys) foreach($citys as $val) {
	            if(strposex($addr, $val['name']) && $val['enabled']) return $val;
	        }
	    }
	    return false;
	}

	/**
	 * 通过城市别名来获取城市
	 * @param  string $domain 城市别名（子域名或目录名）
	 * @return ms_city
	 */
	public static function from_domain($domain)
	{
	    $citys = static::get_citys();
	    $domain = strtolower(trim($domain));
	    if($citys) foreach($citys as $city) {
	        if(strtolower($city['domain']) == $domain) {
	        	return $city;
	        }
	    }
	    return false;
	}

}

/**  */